import dayjs from "dayjs";

/**
 * 页面跳转
 * @param url 要跳转的地址
 * @param delay 延迟时间 单位毫秒
 */
export const goto = (url: string, delay: number = 0): void => {
  setTimeout(() => {
    const target = localStorage.getItem("token")
      ? (url.at(0) === "/" ? "" : "/") + url
      : "/login";
    window.location.href = target;
  }, delay);
};

/**
 * 定义一个公共方法 eval2 使用方法和eval一样
 * @param fn 传入的函数
 * @returns {Function}
 */
export const _eval = (fn: any) => {
  var Fun = Function; // 一个变量指向Function，防止有些前端编译工具报错
  return new Fun("return " + fn)();
};

export class Token {
  public static getToken(key: string) {
    if (Token.isExpire(key)) return;
    // eslint - disable - next - line;
    return _eval("(" + localStorage.getItem(key) + ")").val;
  }
  public static setToken(key: string, val: string, expire = 604800000) {
    const milliseconds = dayjs().valueOf();
    const expireTime = dayjs(milliseconds + expire).format(
      "YYYY-MM-DD HH:mm:ss"
    );
    const obj = {
      expireTime,
      val,
    };
    localStorage.setItem(key, JSON.stringify(obj));
  }

  public static isExpire(key: string) {
    const { expireTime } = JSON.parse(localStorage.getItem(key)! || "");
    const _isExpire = dayjs().isAfter(dayjs(expireTime));
    if (_isExpire) localStorage.removeItem("key");
    return _isExpire;
  }
}
